#!/bin/bash

root_dir="$(pwd)"
sarasa_dir="sarasa"
sarasa_nerd_dir="sarasa-nerd"
mkdir -p $sarasa_nerd_dir
cd $sarasa_nerd_dir

fix_xAvgCharWidth () {
  original_font=$1
  patched_font=$2

  ttx -o "$original_font.ttx" -t "OS/2" $original_font
  ttx -o "$patched_font.ttx" -t "OS/2" $patched_font

  original_x_avg_char_width="$(grep xAvgCharWidth "$original_font.ttx" | cut -d '"' -f 2)"
  echo original xAvgCharWidth is $original_x_avg_char_width
  rm -rf "$original_font.ttx"

  sed -i "" -E "s/xAvgCharWidth value=\"[0-9]+\"/xAvgCharWidth value=\"${original_x_avg_char_width}\"/g" \
    "$patched_font.ttx"

  ttx -o ${patched_font/.ttf/.after.ttf} -m $patched_font "$patched_font.ttx"
  rm -rf "$patched_font.ttx"
  rm $patched_font
  mv ${patched_font/.ttf/.after.ttf} $patched_font
}

for item in ../"$sarasa_dir"/*; do
  if [ -f "$item" ]; then
    extension="${item##*.}"
    if [ "$extension" == "ttf" ]; then
      echo "processing " "$item"
      ../font-patcher -l -c --careful "$item"
      fix_xAvgCharWidth $item $(ls -t | head -1)
    fi
  fi
done

echo "generating ttc from ttf"
cd "$root_dir"
python otf2otc.py -o $sarasa_nerd_dir/sarasa-term-sc-nerd.ttc $sarasa_nerd_dir/sarasa-term-sc-nerd-*.ttf
cd "$sarasa_nerd_dir"
echo "creating tarball of ttf files"
COPYFILE_DISABLE=1 tar -czvf sarasa-term-sc-nerd.ttf.tar.gz sarasa-term-sc-*.ttf
echo "creating tarball of ttc files"
COPYFILE_DISABLE=1 tar -czvf sarasa-term-sc-nerd.ttc.tar.gz sarasa-term-sc-*.ttc
echo "creating 7zip of ttc files"
7zz a -mx9 sarasa-term-sc-nerd.ttc.7z sarasa-term-sc-*.ttc
echo "creating 7zip of ttf files"
7zz a -mx9 sarasa-term-sc-nerd.ttf.7z sarasa-term-sc-*.ttf
cd "$root_dir"
